﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WxYygh.Common;
using WxYygh.Models;
using WxYygh.Models.WeChatPay;

namespace WxYygh.Controllers
{
    public class UserInfoController : Controller
    {
        public static string SecretId = "AKIDYr1wb1f6mCMM7cgOQEn8E5jEXv3EnoFu";
        public static string SecretKey = "lSu9AwTnrgFK9i14rOimgJgpjNlwrb5J";
        [WeChatCheck]
        // GET: UserInfo
        public ActionResult Index(string pbid,string data)
        {
           // checkSfzh();
            string sql = string.Format(@"select * from GZH_BrInfo where openid ='{0}'", Session["openid"].ToString());

            DataSet dt = DbHelperSQL.Query(sql);

            List<UserModel> list = dt.Tables[0].ToDataList<UserModel>();

            ViewBag.list = list;

            ViewBag.num = 5 - list.Count;

            ViewBag.pbid = pbid;
            ViewBag.data = data;

            return View();
        }

        public ActionResult UserInfo(string sfzh,string pbid)
        {
            UserModel model = new UserModel();

            if (!string.IsNullOrEmpty(sfzh)) {
                string sql = string.Format(@"select * from GZH_BrInfo where openid ='{0}' and sfzh='{1}'", Session["openid"].ToString(), sfzh);
                DataSet dt = DbHelperSQL.Query(sql);

                List<UserModel> list = dt.Tables[0].ToDataList<UserModel>();
                model = list[0];
            }

            ViewBag.model = model;
            ViewBag.pbid = pbid;

            return View();
        }
        /// <summary>
        /// 删除病人信息
        /// </summary>
        /// <returns></returns>
        public int delbrxx(string sfzh) {

            string sql = string.Format(@"delete from GZH_BrInfo where openid ='{0}' and sfzh='{1}'", Session["openid"].ToString(), sfzh);
            

            int row = DbHelperSQL.ExecuteSql(sql);

            return row;
        }

        public string insbrxx(UserModel model)
        {
            string result = "0";
            try {
                if (CheckIDCard18(model.sfzh))
                {
                    string sql = string.Format(@"select * from GZH_BrInfo where openid ='{0}' and sfzh='{1}'", Session["openid"].ToString(), model.sfzh);

                    if (DbHelperSQL.Query(sql).Tables[0].Rows.Count > 0)
                    {
                        sql = string.Format(@"update GZH_BrInfo set sjhm='{2}',brxm='{3}',sex='{4}',isdefault='{5}' where openid ='{0}' and sfzh='{1}'",
                             Session["openid"].ToString(), model.sfzh, model.sjhm, model.brxm, model.sex, model.isdefault);
                    }
                    else
                    {
                        sql = string.Format(@"insert into GZH_BrInfo (openid,sfzh,sjhm,brxm,sex,isdefault) values('{0}','{1}','{2}','{3}','{4}','{5}')",
                            Session["openid"].ToString(), model.sfzh.ToUpper(), model.sjhm, model.brxm, model.sex, model.isdefault);
                    }

                    int row = DbHelperSQL.ExecuteSql(sql);

                    if (model.isdefault == 1)
                    {

                        DbHelperSQL.ExecuteSql(string.Format("update GZH_BrInfo set isdefault =0 where openid ='{0}'", Session["openid"].ToString()));

                        DbHelperSQL.ExecuteSql(string.Format("update GZH_BrInfo set isdefault =1 where openid ='{0}' and sfzh='{1}'", Session["openid"].ToString(), model.sfzh.ToUpper()));

                    }
                }
                else {
                    result = "身份证格式有误";
                }
            }
            catch (Exception ex) {
                result = ex.Message;
            }


            return result;
        }


        public static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }

            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }

            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }

        public static int DivRem(int a, int b, out int result)
        {
            result = a % b;
            return (a / b);
        }

        public string checkSfzh() {

            //WxPayData qm = new WxPayData();

            Dictionary<string, string> dics = new Dictionary<string, string>();
            Random ran = new Random();
            dics.Add("Action", "BspIdCardAuth");
            dics.Add("SecretId", SecretId);
            dics.Add("Timestamp", ((int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds).ToString());
            string Nonce = ran.Next(10000, 99999).ToString();
            dics.Add("Nonce",Nonce );
            dics.Add("Region", "all");

            string url = "POSTcsec.api.qcloud.com/v2/index.php?" + getParamSrc(dics);


            string sign = ToHMACSHA1(url, SecretKey);

            sign = HttpUtility.UrlEncode(sign, Encoding.UTF8);



            url = "https://csec.api.qcloud.com/v2/index.php";

            //qm.SetValue("channelId", "hospitalAPI");


            //qm.SetValue("Action", "BspIdCardAuth");
            //qm.SetValue("SecretId", SecretId);
            //qm.SetValue("Timestamp", 1463122059);
            //qm.SetValue("Nonce", Nonce);
            //qm.SetValue("Region", "all");
            //qm.SetValue("Signature", sign);
            //qm.SetValue("orderNo", DateTime.Now.ToString("yyyyMMddHHmmss"));
            //qm.SetValue("name", "朱建飞");
            //qm.SetValue("idNumber", "330501199002022213");

            dics.Add("Signature", sign);
            dics.Add("orderNo", DateTime.Now.ToString("yyyyMMddHHmmss"));
            dics.Add("name", "朱建飞");
            dics.Add("idNumber", "330501199002022213");


            string response = HttpHelper.Instance.post(url, getParamSrc(dics));
            JObject json = JObject.Parse(response);

            

            return "";
        }
        /// <summary>
        /// 对所有请求参数按参数名做字典序升序排列
        /// </summary>
        /// <param name="paramsMap"></param>
        /// <returns></returns>
        public static String getParamSrc(Dictionary<string, string> paramsMap)
        {
            var vDic = (from objDic in paramsMap orderby objDic.Key ascending select objDic);
            StringBuilder str = new StringBuilder();
            foreach (KeyValuePair<string, string> kv in vDic)
            {
                string pkey = kv.Key;
                string pvalue = kv.Value;
                str.Append(pkey + "=" + pvalue + "&");
            }

            String result = str.ToString().Substring(0, str.ToString().Length - 1);


            return result;
        }
        /// <summary>
        /// HMAC-SHA1 签名
        /// </summary>
        /// <param name="encryptText"></param>
        /// <param name="encryptKey"></param>
        /// <returns></returns>
        public static string ToHMACSHA1(string encryptText, string encryptKey)
        {
            //HMACSHA1加密
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(encryptKey);
            byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(encryptText);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            return Convert.ToBase64String(hashBytes);
        }


    }
}